package com.css.apps.base.sysjob.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.css.apps.base.sysjob.model.SysJob;
import com.css.core.configuration.Environment;
import com.css.db.query.QueryCache;
import com.css.db.query.TransactionCache;
import com.css.util.Ajax;
import com.css.util.ListUtil;
import com.css.util.Md5Util;
import com.css.util.Messages;
import com.css.util.StringHelper;
import com.css.webbase.webwork.action.AdminAction;
import com.opensymphony.xwork.Action;

public class AddOrgJobSysRoles extends AdminAction {
	private static final long serialVersionUID = 9214193652418318580L;
	private static Log log = LogFactory.getLog(AddOrgJobSysRoles.class);
	private String orgId;
	private String jobId;
	private String applyPermission;

	@SuppressWarnings("unchecked")
	@Override
	protected String adminGo() {
		TransactionCache tx = null;
		List<SysJob> delSysJobs = null;
		try {
			if (!checkField()) {
				result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.fieldEmpty"));
				return Action.ERROR;
			}
			List<String> sysJobIds = new QueryCache("select a.uuid from SysJob a where a.orgId =:orgId and a.jobId =:jobId")
					.setParameter("orgId", orgId).setParameter("jobId", jobId).list();
			if (!ListUtil.isLstEmpty(sysJobIds)) {
				delSysJobs = QueryCache.idToObj(SysJob.class, sysJobIds);
			}
			StringBuffer uuid = new StringBuffer(orgId+jobId);
			Map<String, List<String>> map = new HashMap<String, List<String>>();
			List<SysJob> sysJobs = new ArrayList<>();
			SysJob sysJob = null;
			map = getAccountSysRole(applyPermission);
			Set<String> keys = map.keySet();
			Iterator<String> iterator = keys.iterator();
			while (iterator.hasNext()) {
				String key = iterator.next();
				List<String> roles = map.get(key);
				uuid.append(key);
				for (String role : roles) {
					sysJob = new SysJob();
					uuid.append(role);
					String md5uuid = Md5Util.MD5Encode(uuid.toString());
					sysJob.setUuid(md5uuid);
					sysJob.setJobId(jobId);
					sysJob.setOrgId(orgId);
					sysJob.setSysId(key);
					sysJob.setRoleId(role);
					sysJobs.add(sysJob);
				}
			}
			tx = new QueryCache().getTransaction();
			tx.delete(delSysJobs);
			tx.save(sysJobs);
			tx.commit();
			result = Ajax.JSONResult(Environment.RESULT_CODE_SUCCESS, Messages.getString("systemMsg.success"));
			return Action.SUCCESS;
		} catch (Exception ex) {
			if (tx != null)
				tx.rollback();
			log.error(ex.getMessage(), ex);
			result = Ajax.JSONResult(Environment.RESULT_CODE_ERROR, Messages.getString("systemMsg.dbFaild"));
			return Action.ERROR;
		}
	}
	
	// 解析申请系统权限字符串
	public static Map<String, List<String>> getAccountSysRole(String applyPermission) {
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		List<String> list = null;
		if (StringHelper.isNotEmpty(applyPermission)) {
			String authdesc = applyPermission;
			String[] auth = authdesc.split("@");
			for (int i = 0; i < auth.length; i++) {
				String[] sysIdAndrole = auth[i].split(":");
				String[] roleIds = sysIdAndrole[1].split(",");
				list = new ArrayList<>();
				for (String roleId : roleIds) {
					list.add(roleId);
				}
				map.put(sysIdAndrole[0], list);
			}
		}
		return map;
	}

	public boolean checkField() {
		if (StringHelper.isEmpty(orgId) || StringHelper.isEmpty(jobId) || StringHelper.isEmpty(applyPermission))
			return false;
		return true;
	}
	
	public String getOrgId() {
		return orgId;
	}

	public void setOrgId(String orgId) {
		this.orgId = orgId;
	}

	public String getApplyPermission() {
		return applyPermission;
	}

	public void setApplyPermission(String applyPermission) {
		this.applyPermission = applyPermission;
	}

	public String getJobId() {
		return jobId;
	}

	public void setJobId(String jobId) {
		this.jobId = jobId;
	}
}